package cn.genmer.test.security.encryption;
 
import java.math.BigInteger;
 
public class RC4 {
    // 指定一个密钥
    public static String RC4_key = "7654qwe¥%&";
 
    // 解密
    public static String decry_RC4(String data) {
        if (data == null) {
            return null;
        }
        byte[] data_b = new BigInteger(data).toByteArray();
        byte[] data_decode = RC4Base(data_b, RC4_key);
        String res = new BigInteger(data_decode).toString();
        return res;
    }
 
    // 加密
    public static String encry_RC4(String data) {
        if (data == null) {
            return null;
        }
        byte[] data_b = new BigInteger(data).toByteArray();
        byte[] data_encode = RC4Base(data_b, RC4_key);
        String res = new BigInteger(data_encode).toString();
        return res;
    }
 
    private static byte[] initKey(String aKey) {
        byte[] b_key = aKey.getBytes();
        byte state[] = new byte[256];
 
        for (int i = 0; i < 256; i++) {
            state[i] = (byte) i;
        }
        int index1 = 0;
        int index2 = 0;
        if (b_key == null || b_key.length == 0) {
            return null;
        }
        for (int i = 0; i < 256; i++) {
            index2 = ((b_key[index1] & 0xff) + (state[i] & 0xff) + index2) & 0xff;
            byte tmp = state[i];
            state[i] = state[index2];
            state[index2] = tmp;
            index1 = (index1 + 1) % b_key.length;
        }
        return state;
    }
 
    private static byte[] RC4Base(byte[] input, String mKkey) {
        int x = 0;
        int y = 0;
        byte key[] = initKey(mKkey);
        int xorIndex;
        byte[] result = new byte[input.length];
 
        for (int i = 0; i < input.length; i++) {
            x = (x + 1) & 0xff;
            y = ((key[x] & 0xff) + y) & 0xff;
            byte tmp = key[x];
            key[x] = key[y];
            key[y] = tmp;
            xorIndex = ((key[x] & 0xff) + (key[y] & 0xff)) & 0xff;
            result[i] = (byte) (input[i] ^ key[xorIndex]);
        }
        return result;
    }
 
    public static void main(String[] args) {
        String phone_str = "13644040598";
        String enPhone = encry_RC4(phone_str);
        System.out.println("加密后的手机号:  "+enPhone);
        System.out.println("加密后的手机号长度:  "+enPhone.toString().length());
        String phone = decry_RC4(enPhone);
        System.out.println("解密后的手机号:  "+phone);
    }
}
//-----加密前----------加密后---------
// 18612345670     299598236947
// 18612345671     299598236946
// 18612345672     299598236957
// 18612345673     299598236956
// 18612345674     299598236959
// 18612345675     299598236958
// 18612345676     299598236953
// 18612345677     299598236952
// 18612345678     299598236955
// 18612345679     299598236954
// 28612345679     305974356250
// 38612345679     315301180698
 